/**
 * HTTP 拦截器
 * 处理请求和响应的拦截逻辑
 */
import { ElMessage } from "element-plus"
import { useUsersStore } from "@/stores/modules/user"

/**
 * 设置请求拦截器
 * @param {AxiosInstance} instance - axios 实例
 */
export function setupRequestInterceptor(instance) {
  instance.interceptors.request.use(
    (config) => {
      // Token 注入
      const usersStore = useUsersStore()
      if (usersStore.token) {
        config.headers.Authorization = `Bearer ${usersStore.token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
}

/**
 * 设置响应拦截器
 * @param {AxiosInstance} instance - axios 实例
 */
export function setupResponseInterceptor(instance) {
  instance.interceptors.response.use(
    (response) => {
      const { data } = response
      
      if (data.code !== undefined) {
        if (data.code === 200) {
          return {
            code: data.code,
            data: data.data,
            message: data.message || 'success'
          }
        } else {
          const errorMessage = data.message || '业务处理失败'
          ElMessage.error(errorMessage)
          return Promise.reject(new Error(errorMessage))
        }
      }

      // 非标准格式的响应，包装成规范格式
      return {
        code: 200,
        data: data,
        message: 'success'
      }
    },
    (error) => {
      const { response } = error
      const usersStore = useUsersStore()

      if (response) {
        const { status, data } = response

        switch (status) {
          case 401:
            ElMessage.error('登录已过期，请重新登录')
            usersStore.logout()
            break

          case 403:
            ElMessage.error('没有权限访问该资源')
            break

          case 404:
            ElMessage.error('请求的资源不存在')
            break

          case 422:
            const validationMessage = data.message || '提交的数据格式不正确'
            ElMessage.error(validationMessage)
            break

          case 500:
          case 501:
          case 502:
          case 503:
            ElMessage.error('服务器发生错误，请稍后重试')
            break

          default:
            ElMessage.error(data.message || `请求错误 (${status})`)
            break
        }
      } else if (error.request) {
        ElMessage.error('网络连接异常，请检查您的网络')
      } else {
        ElMessage.error('请求发送失败，请联系技术支持')
      }

      return Promise.reject(error)
    }
  )
}

/**
 * 设置所有拦截器
 * @param {AxiosInstance} instance - axios 实例
 */
export function setupInterceptors(instance) {
  setupRequestInterceptor(instance)
  setupResponseInterceptor(instance)
}
